﻿function Path(stringPath) {
    var match = stringPath.match(/__[a-zA-Z0-9]+$/);
    this.stringPath = stringPath;
    if (match) {
        this.functor = match[0].substring(2);
        this.stringPathParts = this.stringPath.substring(0, this.stringPath.length - match[0].length);
    } else {
        this.stringPathParts = this.stringPath;
    }
}

Path.getItemId = function(id) {
    var path = new Path(id);
    return path.getNodePath();
}

Path.getLast = function(path) {
    var pathObject = new Path(path);
    return pathObject.getLastPart();
}

Path.getIndexedId = function(id, index) {
    return id + '_' + index;
}

Path.getUnindexedId = function(id) {
    return id.substring(0, id.lastIndexOf('_'));
}

Path.getReindexedId = function(id, index) {
    return Path.getIndexedId(Path.getUnindexedId(id), index);
}

Path.getSiblingId = function(id, index) {
    if (index == null || index == 0) index = 1;
    if (index == -1) index = '';
    var underscoreIndex = id.lastIndexOf("_");
    return id.substring(0, underscoreIndex) + "_" + index;
}

Path.prototype = {
    getIndex: function() {
        return this.getLastPart().getIndex();
    },

    isNodePath: function() {
        return (this.functor == null);
    },

    getPathParts: function() {
        if (this.pathParts == null) {
            this.pathParts = new Array();
            var split = this.stringPathParts.split('_');
            var previousStart = 0;
            for (var i = 0; i < split.length; i++) {
                var asInt = parseInt(split[i]);
                if (!isNaN(asInt)) {
                    var nextPathPart = split.slice(previousStart, i + 1).join('_');
                    this.pathParts[this.pathParts.length] = nextPathPart;
                    previousStart = i + 1;
                }

            }
        }

        return this.pathParts;
    },

    getParentPath: function() {
        var parts = this.getPathParts();
        if (parts.length == 0) return null;
        return parts.slice(0, parts.length - 1).join('_');
    },

    getLastPart: function() {
        var array = this.getPathParts();
        if (array.length == 0) return null;
        return array[array.length - 1];
    },

    getNodePath: function() {
        return this.stringPathParts;
    },

    getPrototypePath: function() {
        return this.stringPathParts.replace(/_(\d+)/g, "_0");
    },

    getFunctor: function() {
        return this.functor;
    },

    getString: function() {
        return this.stringPath;
    }
}

